﻿namespace LeadMaster.Controllers
{
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Entity;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  using LeadMaster.Models;
  using LeadMaster.DAL;
  using LeadMaster.Helpers;
  using LeadMaster.Interfaces;
  using System.Web.Security;
  using System.IO;
  using LeadMaster.ViewModels;

  [Authorize]
    public class CallCentresController : Controller
    {
        private DunsmoreContext db = new DunsmoreContext();

        public ActionResult Index(string personType="I")
        {
            Maintenance.inMaintenance = true;
            List<CallCentres> cclist = new List<CallCentres>();
            ViewBag.PersonType = personType;
            Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
            string userName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
            CallCentres cc = db.CallCentres
                              .Where(m => m.UserName == userName)
                              .FirstOrDefault();
            switch (personType)
            {
              case "N" :
                cclist = db.CallCentres.Where(m => m.Category == personType && m.OwnedBy == cc.CallCentreID).ToList();
                break;
              case "D":
                cclist = db.CallCentres.Where(m => m.Category == personType && m.OwnedBy == cc.CallCentreID).ToList();
                break;
              case "C":
                cclist = db.CallCentres.Where(m => m.Category == personType).ToList();
                break;
              case "O":
                cclist = db.CallCentres.Where(m => m.Category == personType).ToList();
                ViewBag.IsIntroducer = true;
                break;
              case "I":
                cclist = db.CallCentres.Where(m => m.Category == personType).ToList();
                ViewBag.IsIntroducer = true;
                break;
              case "E":
                cclist = db.CallCentres.Where(m => m.Category == personType && m.OwnedBy == cc.CallCentreID).ToList();
                break;
              default:
                break;
            }
            return View(cclist);
        }

        public ActionResult Details(int id = 0)
        {
            CallCentres callcentres = db.CallCentres.Find(id);
            if (callcentres == null)
            {
                return HttpNotFound();
            }
            return View(callcentres);
        }

        public ActionResult Create(string personType = "I")
        {
            Maintenance.inMaintenance = true;
            CallCentres cc=new CallCentres();
            ViewBag.PersonType = personType;
            if (personType=="C")
            {
              cc.OwnedBy = db.CallCentres.Where(m => m.Category == "C" && m.OwnedBy == null).FirstOrDefault().CallCentreID;
              ViewBag.EnterUser = true;
            }
            else if ("NE".IndexOf(personType)!=-1)
            {
              Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
              string userName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
              CallCentres currentInstaller = db.CallCentres
                                .Where(m => m.UserName == userName)
                                .FirstOrDefault();
              cc.OwnedBy = currentInstaller.CallCentreID;
              ViewBag.EnterUser = true;
            }
            cc.Category = personType;
            ViewBag.RegionsID = new SelectList(db.Regions, "RegionsID", "Description");
            return View(cc);
        }

        [HttpPost]
        public ActionResult Create(CallCentres callcentres, string PersonType, string Username="", string Password="")
        {
            if (ModelState.IsValid)
            {
                callcentres.active = true;
                callcentres.CallCentre = callcentres.Contact1;
                callcentres.potitle = callcentres.Contact1;
                callcentres.Category = PersonType;
                db.CallCentres.Add(callcentres);
                db.SaveChanges();
                if (Username.Length > 0)
                {
                  RegisterModel model = new RegisterModel();
                  model.UserName = Username;
                  model.Password = Password;
                  model.Email = callcentres.Email1;
                  AccountController account = new AccountController();
                  MembershipCreateStatus createStatus;
                  Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
                  if (createStatus == MembershipCreateStatus.Success)
                  {
                    AllocateRole(model.UserName, PersonType);
                    return RedirectToAction("Index", new { personType = PersonType });
                  }
                }

                return RedirectToAction("Index", new { personType=PersonType });
            }
            return View(callcentres);
        }

        public ActionResult Edit(int id=0, string personType="X")
        {
          Maintenance.inMaintenance = true;
          int currentID = 0;
          if (id==0)
          {
            currentID = GetID();  
          }
          CallCentres callcentres;
          if (id==0)
          {
            callcentres = db.CallCentres.Find(currentID);
            ViewBag.CurrentUser = true;
          }
          else
          {
            callcentres = db.CallCentres.Find(id);
            ViewBag.CurrentUser = false;
          }
          
          if (callcentres == null)
          {
              return HttpNotFound();
          }
          ViewBag.RegionsID = new SelectList(db.Regions, "RegionsID", "Description",callcentres.RegionsID);
          return View(callcentres);
        }

        [HttpPost]
        public ActionResult Edit(CallCentres callcentres, string PersonType, string Username="", string Password="")
        {
            if (ModelState.IsValid)
            {
              callcentres.CallCentre = callcentres.Contact1;
              callcentres.potitle = callcentres.Contact1;
              if (callcentres.TCConfirmedDate == null && callcentres.ConfirmedTC == true)
              {
                callcentres.TCConfirmedDate = DateTime.Now;
              }
              db.Entry(callcentres).State = EntityState.Modified;
              db.SaveChanges();
              if (Username.Length > 0 && !db.Users.Any(m => m.UserName==Username))
              {
                RegisterModel model = new RegisterModel();
                model.UserName = Username;
                model.Password = Password;
                model.Email = callcentres.Email1;
                AccountController account = new AccountController();
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
                if (createStatus == MembershipCreateStatus.Success)
                {
                  AllocateRole(model.UserName, PersonType);
                  return RedirectToAction("Index", new { personType = PersonType });
                }
              }
              else if (Username.Length > 0 && db.Users.Any(m => m.UserName==Username))
              {
                Users user = db.Users.Where(m => m.UserName == Username).FirstOrDefault();
                Guid userID = user.UserID;
                if (user.UserName != Username)
                {
                  user.UserName = Username;
                  db.Entry(user).State = EntityState.Modified;
                  db.SaveChanges();
                }
                if (!db.UsersInRoles.Any(m => m.UserId==userID))
                {
                AllocateRole(Username, PersonType);  
                }
              }
              return RedirectToAction("Index","Home");
            }
            return View(callcentres);
        }

        public void AllocateRole(string userName, string personType)
        {
          // now registered, allocate the correct role
          switch (personType)
          {
            case "I": // introducer or agent
              Roles.AddUserToRole(userName, "Introducer");
              break;
            case "N": // installer
              Roles.AddUserToRole(userName, "Installer");
              break;
            case "C": // love your earth
              Roles.AddUserToRole(userName, "Client");
              break;
            case "E": // engineer
              Roles.AddUserToRole(userName, "Engineer");
              break;
            case "D": // Deagda
              Roles.AddUserToRole(userName, "Deagda");
              break;
            default:
              break;
          }
        }

        public ActionResult Delete(int id = 0)
        {
            CallCentres callcentres = db.CallCentres.Find(id);
            if (callcentres == null)
            {
                return HttpNotFound();
            }
            return View(callcentres);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            CallCentres callcentres = db.CallCentres.Find(id);
            string personType = callcentres.Category;
            db.CallCentres.Remove(callcentres);
            db.SaveChanges();
            return RedirectToAction("Index", new { personType = personType});
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        private int GetID()
        {
          Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
          string currentUserName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
          int callCentreID = db.CallCentres
            .Where(m => m.UserName == currentUserName)
            .Select(m => m.CallCentreID)
            .FirstOrDefault();

          return callCentreID;
        }

        [HttpPost]
        public ContentResult Upload()
        {
          var r = new List<ViewDataUploadFilesResult>();

          foreach (string file in Request.Files)
          {
            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
              continue;

            string savedFileName = Path.Combine(Server.MapPath("~/ClientImages"), Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName); // Save the file

            r.Add(new ViewDataUploadFilesResult()
            {
              Name = hpf.FileName,
              Length = hpf.ContentLength,
              Type = hpf.ContentType
            });

          }
          // Returns json
          return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
        }

        [HttpPost]
        public JsonResult RegisterPicFile(int id, string filename)
        {
          CallCentres cc = db.CallCentres.Find(id);
          if (cc!=null)
          {
            cc.pic = filename;
            db.Entry(cc).State = EntityState.Modified;
          }
          db.SaveChanges();
          string pathos = Server.MapPath("~/ClientImages/" + filename);
          decimal aspectRatio = 1;
          if (System.IO.File.Exists(pathos))
          {
            System.Drawing.Image img = System.Drawing.Image.FromFile(pathos);
            aspectRatio = (decimal)img.Width / (decimal)img.Height;
          }
          return Json(aspectRatio, JsonRequestBehavior.AllowGet);
        }

        [ChildActionOnly]
        public ActionResult ShowPic()
        {
          int id = GetID();
          CallCentres cc=db.CallCentres.Find(id);
          ViewBag.picName = "";
          ViewBag.AspectRation = 1;
          if (cc!=null)
          {
            ViewBag.picName = cc != null ? cc.pic : "";
            string pathos = Server.MapPath("~/ClientImages/" + ViewBag.picName);
            decimal aspectRatio = 1;
            if (System.IO.File.Exists(pathos))
            {
              System.Drawing.Image img = System.Drawing.Image.FromFile(pathos);
              aspectRatio = (decimal)img.Width / (decimal)img.Height;
            }
            ViewBag.AspectRatio = aspectRatio;  
          }
          ViewModelPerson viewModel = new ViewModelPerson();
          viewModel = SiteValues.FetchIntroInfo();
          Session["PersonType"] = viewModel.PersonType;
          return PartialView(viewModel);
        }

        public ActionResult TermsConditions()
        {
          return PartialView();
        }

        public ActionResult CancelProfile(CallCentres cc)
        {
          CallCentres originalCC = db.CallCentres.Find(cc.CallCentreID);
          if (ModelState.IsValid)
          {
            originalCC.pic = cc.pic;
            db.Entry(originalCC).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
          }
          return RedirectToAction("Index", "Home");
        }

        public ActionResult IntroducerFees(int introducerID=0)
        {
          ViewModelIntroducerFee viewModel = new ViewModelIntroducerFee();
          viewModel.ListSectors=db.Sectors.OrderBy(m => m.Sector).ToList();
          viewModel.Introducers = new SelectList(db.CallCentres.Where(m => m.Category == "I"),"CallCentreID","Contact1", introducerID);
          viewModel.IntroducerFee= new IntroducerFees();
          viewModel.Fees = new List<decimal>();
          if (introducerID != 0)
          {
            foreach (var item in viewModel.ListSectors)
            {
              IntroducerFees introducerFees = db.IntroducerFees.Where(m => m.CallCentresID == introducerID && m.SectorsID == item.SectorID).FirstOrDefault();
              if (introducerFees != null)
              {
                viewModel.Fees.Add(introducerFees.Fee);
              }
              else
              {
                viewModel.Fees.Add(Convert.ToDecimal(item.DefaultCCFee));
              }

            }
            viewModel.ListIntroducerFees = db.IntroducerFees.Where(m => m.CallCentresID == introducerID).ToList();
          }
          else
          {
            for (int i = 0; i < viewModel.ListSectors.Count(); i++)
            {
              viewModel.Fees.Add(0m);
            }
          }

          viewModel.IntroducerFeeID = introducerID;
          return View(viewModel);
        }


        [HttpPost]
        public ActionResult IntroducerFees(ViewModelIntroducerFee viewModel)
        {
          IntroducerFees introducerFees;
          int sectorID = 0;
          for (int i = 0; i < viewModel.ListSectors.Count(); i++)
          {
            sectorID = viewModel.ListSectors[i].SectorID;
            try
            {
              introducerFees = db.IntroducerFees.Where(m => m.CallCentresID == viewModel.IntroducerFeeID && m.SectorsID == sectorID).FirstOrDefault();
              if (introducerFees != null)
              {
                introducerFees.Fee = viewModel.Fees[i];
                db.Entry(introducerFees).State = EntityState.Modified;
              }
              else
              {
                introducerFees = new IntroducerFees();
                introducerFees.CallCentresID = viewModel.IntroducerFeeID;
                introducerFees.SectorsID = viewModel.ListSectors[i].SectorID;
                introducerFees.Fee = viewModel.Fees[i];
                db.IntroducerFees.Add(introducerFees);
              }
            }
            catch (Exception)
            {
              introducerFees = new IntroducerFees();
              introducerFees.CallCentresID = viewModel.IntroducerFeeID;
              introducerFees.SectorsID = viewModel.ListSectors[i].SectorID;
              introducerFees.Fee = viewModel.Fees[i];
              db.IntroducerFees.Add(introducerFees);
            }
          }
          db.SaveChanges();
          return RedirectToAction("IntroducerFees", new { introducerID = viewModel.IntroducerFeeID });
        }

        public ActionResult AssignClassification()
        {
          ViewBag.CallCentreID = new SelectList(db.CallCentres.Where(m => m.Category == "I"), "CallCentreID", "Contact1");
          ViewBag.SectorID = new SelectList(db.Sectors, "SectorID", "Sector");
          Classification classification = new Classification();
          return View(classification);
        }

        [HttpPost]
        public ActionResult AssignClassification(Classification classification)
        {
          Classification editingClassification = db.Classification.Where(m => m.CallCentreID == classification.CallCentreID && m.SectorID == classification.SectorID).FirstOrDefault();
          if (editingClassification != null)
          {
            editingClassification.NU_New = classification.NU_New;
            editingClassification.NU_Research = classification.NU_Research;
            editingClassification.NU_Past = classification.NU_Past;
            editingClassification.NU_Face = classification.NU_Face;
            editingClassification.U_New = classification.U_New;
            editingClassification.U_Face = classification.U_Face;
            editingClassification.U_Past = classification.U_Past;
            editingClassification.U_Research = classification.U_Research;
            db.Entry(editingClassification).State = EntityState.Modified;
          }
          else
          {
            db.Classification.Add(classification);
          }
          db.SaveChanges();
          ViewBag.CallCentreID = new SelectList(db.CallCentres.Where(m => m.Category == "I"), "CallCentreID", "Contact1",classification.CallCentreID);
          ViewBag.SectorID = new SelectList(db.Sectors, "SectorID", "Sector", classification.SectorID);
          return View(classification);
        }

        [HttpGet]
        public ActionResult UpdateClassification(int callCentreID, int sectorID)
        {
          IClassification classification = db.Classification.Where(m => m.CallCentreID == callCentreID && m.SectorID == sectorID).FirstOrDefault();
          if (classification!=null)
          {
            List<ClassificationJson> cj=new List<ClassificationJson>();
		        cj.Add(new ClassificationJson {Classification="NU_Face", ClassVal=classification.NU_Face});
            cj.Add(new ClassificationJson { Classification = "NU_Research", ClassVal = classification.NU_Research });
            cj.Add(new ClassificationJson {Classification="NU_Past", ClassVal=classification.NU_Past});
            cj.Add(new ClassificationJson { Classification = "NU_Face", ClassVal = classification.NU_Face });
            cj.Add(new ClassificationJson { Classification = "U_New", ClassVal = classification.U_New });
            cj.Add(new ClassificationJson { Classification = "U_Research", ClassVal = classification.U_Research });
            cj.Add(new ClassificationJson { Classification = "U_Past", ClassVal = classification.U_Past });
            cj.Add(new ClassificationJson { Classification = "U_Face", ClassVal = classification.U_Face });
            return Json(cj, JsonRequestBehavior.AllowGet);
          }
          classification = new Classification();
          return Json(classification, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Testjson()
        {
          string testval = "Testing";
          return Json(testval, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AutoAllocate()
        {
          GenericRepository gr = new GenericRepository();
          gr.AutoAllocateInstallers();
          return View();
        }

    }
}